﻿




using System.Collections.Generic;
using System.Web.Mvc;
using Hotpot.Models;
using Hotpot.Modules.Blogs.Models;
using Hotpot.Modules.Blogs.Services;
using Hotpot.Modules.Blogs.ViewModels;
using Hotpot.ViewModels;

namespace Hotpot.Modules.Blogs.Filters
{
    public class ArchiveListActionFilter : IActionFilter
    {
        private readonly IPostService postService;
        private readonly IBlogService blogService;

        public ArchiveListActionFilter(IPostService postService, IBlogService blogService)
        {
            this.postService = postService;
            this.blogService = blogService;
        }

        #region IActionFilter Members

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HotpotViewModel model = filterContext.Controller.ViewData.Model as HotpotViewModel;

            if (model != null)
            {
                IEnumerable<KeyValuePair<ArchiveData, int>> archives;
                INamedEntity container;
                Blog blog = blogService.GetBlog(filterContext.RouteData.Values["blogName"] as string);

                if (blog != null)
                {
                    archives = postService.GetArchives(blog);
                    container = blog;
                }
                else
                {
                    archives = postService.GetArchives();
                    container = new BlogHomePageContainer();
                }

                model.AddModelItem(new ArchiveViewModel(archives, container));
            }
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionParameters.ContainsKey("pageSize"))
                filterContext.ActionParameters["pageSize"] = 20;
        }

        #endregion
    }
}
